package com.tnl.hunter.webchat.controller;

import com.biz.hunter.dao.*;
import com.biz.hunter.db.entity.*;
import com.biz.system.config.WebchatServiceConstant;
import com.biz.wechat.annotation.OAuthRequired;
import com.biz.wechat.util.RadomUtils;
import com.biz.wechat.util.SignUtil;
import com.jfinal.weixin.sdk.api.ApiResult;
import com.jfinal.weixin.sdk.api.TemplateData;
import com.jfinal.weixin.sdk.api.TemplateMsgApi;
import com.jfinal.weixin.sdk.utils.HttpUtils;
import com.tnl.hunter.webchat.common.MsgService;
import com.tnl.hunter.webchat.utils.DateUtils;
import com.tnl.hunter.webchat.utils.SMSService;
import com.tnl.hunter.webchat.utils.WxaTemplateUtil;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.io.FilenameUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Controller
public class HunterController {

    private static final Logger logger = LoggerFactory
            .getLogger(HunterController.class);

    @Autowired
    private WXUserDAO userDAO;
    @Autowired
    private DomainDAO domainDAO;
    @Autowired
    private HunterCompanyDAO hunterCompanyDAO;
    @Autowired
    private HunterDAO hunterDAO;
    @Autowired
    private CompanyDAO companyDAO;
    @Autowired
    private CityDAO cityDAO;
    @Autowired
    private JobDAO jobDAO;
    @Autowired
    private JobTitleDAO roleDAO;
    @Autowired
    private OrderDAO orderDAO;
    @Autowired
    private OrderDescDAO orderDescDAO;
    @Autowired
    private EvaluateDAO evaluateDAO;
    @Autowired
    private WxAppUserDAO wxAppUserDAO;
    @Autowired
    private SysConfigRepo sysConfigService;
    @Autowired
    private PersonDAO personDAO;
    @Autowired
    private EmployeeDAO employeeDAO;
    @Autowired
    private TbFormDAO tbFormDAO;

    @Autowired
    private DictionaryDAO dictionaryDAO;

    @Autowired
    private MsgService msgService;

    @Autowired
    private OrderResumeDAO orderResumeDAO;


    @Autowired
    private OrderSalaryDAO salaryDAO;

    @Autowired
    private OrderPlanDAO planDAO;

    @Autowired
    private OrderInterviewDAO interviewDAO;

    @Autowired
    private OrderLeaveDAO leaveDAO;

    private UserInfo user = null;

    // =================菜单入口 -- 我的认证 第一步
    @OAuthRequired
    @RequestMapping(value = "wechat/hunter/main.page", method = RequestMethod.GET)
    public String toViewBindPhonePage(HttpServletRequest request, Model model) {

        String result = getCurrentUser(request);

        if (StringUtils.hasText(result)) {
            return result;
        }

        /* */
        String ticket = sysConfigService.getJsTicket();
        logger.debug("js api ticket is " + ticket);
        String url = request.getRequestURL().toString();
        if (!StringUtils.isEmpty(request.getQueryString())) {
            url = url + "?" + request.getQueryString();
        }
        url = url.replace("http", "https");
        logger.debug("request url is " + url);

        Map<String, String> jsconfig = SignUtil.getJSSignature(ticket, url);

        jsConfig config = new jsConfig();
        config.setAppid(WebchatServiceConstant.APPID);
        config.setCurrenttimestamp(jsconfig.get("timestamp"));
        config.setNonceStr(jsconfig.get("nonceStr"));
        config.setSignatureStr(jsconfig.get("signature"));

        model.addAttribute("config", config);
        /* */

        String openid = user.getOpenid();

        Hunter hunter = hunterDAO.getByActivateHunter(openid);
        if (hunter != null) {
            List<OrderDesc> orderDescList = orderDescDAO.getAllByHunterId(hunter.getId());
            String orderDescName = orderDescList.stream().map(OrderDesc::getName).collect(Collectors.joining("/"));
            model.addAttribute("orderDesc", orderDescName);
            // if (hunter.getApproved() != -1) {
            if (hunter.getState().equals(Hunter.State.approving.toString())) {
                // 认证中
                model.addAttribute("hunter", hunter);
                return "wechat/headhunter/hunter/lietouxinxi";
            }
            if (hunter.getState().equals(Hunter.State.approved.toString())) {
                // 认证
                model.addAttribute("hunter", hunter);
                return "wechat/headhunter/hunter/lietouxinxi";
            }
            if (hunter.getState().equals(Hunter.State.binded.toString())) {
                // 绑定phone之后
                model.addAttribute("hunter", hunter);
                return "wechat/headhunter/hunter/lietouxinxi1";
            }
        }

        hunter = new Hunter();
        hunter.setOpenid(openid);
        model.addAttribute("hunter", hunter);
        return "wechat/headhunter/hunter/validateCellPhone";
    }

	/*private jsConfig getWechatJsConf(HttpServletRequest request) {

		String ticket = sysConfigService.getJsTicket();
		logger.debug("js api ticket is " + ticket);
		String url = request.getRequestURL().toString();
		if (!StringUtils.isEmpty(request.getQueryString())) {
			url = url + "?" + request.getQueryString();
		}
		logger.debug("request url is " + url);

		Map<String, String> jsconfig = SignUtil.getJSSignature(ticket, url);

		jsConfig config = new jsConfig();
		config.setAppid(WebchatServiceConstant.APPID);
		config.setCurrenttimestamp(jsconfig.get("timestamp"));
		config.setNonceStr(jsconfig.get("nonceStr"));
		config.setSignatureStr(jsconfig.get("signature"));
		return config;
	}*/

    private String getCurrentUser(HttpServletRequest request) {

        HttpSession session = request.getSession();
        String openid = (String) session.getAttribute("OpenId");
        logger.debug("openid is " + openid);
        if (StringUtils.isEmpty(openid)) {
            logger.info("该网页须在微信平台访问");
            return "wechat/headhunter/errorpage?msg+该网页须在微信平台访问";
        }
        user = userDAO.getByOpenId(openid);
        if (user == null) {
            logger.info("the openid=" + openid + " is not subscribed");
            return "wechat/headhunter/errorpage";
        }
        return null;
    }

    @OAuthRequired
    @RequestMapping(value = "wechat/headhunter/hunter/sendSecurityCode.do", method = RequestMethod.GET)
    public @ResponseBody
    Map<String, Object> genSecurityCode(HttpServletRequest request, String phone, Model model) {
        Map<String, Object> returnMap = new HashMap<String, Object>();
        getCurrentUser(request);
        // check email/phone is generated and not expired

        if (phone == null || phone.length() < 1) {
            returnMap.put("errorcode", "1");
            returnMap.put("msg", "手机号为空!");
            return returnMap;
        }
        HttpSession session = request.getSession();
        String openid = (String) session.getAttribute("OpenId");
        if (openid == null || openid.length() < 1) {
            returnMap.put("errorcode", "1");
            returnMap.put("msg", "openid为空!");
            return returnMap;
        }
        Hunter hunter = hunterDAO.getByPhoneandOpenId(phone, openid);
        String secureCode = null;
        if (hunter != null) {
            // get expiredDate
            secureCode = hunter.getSecureCode();
        } else {
            RadomUtils radom = new RadomUtils();
            // gen code
            secureCode = radom.getRadom(4);
            // save code

            hunter = new Hunter();
            hunter.setOpenid(openid);
            hunter.setPhone(phone);
            hunter.setSecureCode(secureCode);// 重复的
            hunter.setState(Hunter.State.generated.toString());
            // hunter.setBinded(1);
            hunter.setActive(1);
            java.util.Date timeDate = new Date();// util类型
            long time = timeDate.getTime();
            java.sql.Timestamp dateTime = new java.sql.Timestamp(time);// Timestamp类型,timeDate.getTime()返回一个long型

            hunter.setExpiredTime(dateTime);
            hunterDAO.saveSecureCode(hunter);
        }
        // send out code
        // mailService.sendMail(email, secureCode);
        try {
            SMSService.sendSMS(phone, secureCode);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            returnMap.put("errorcode", "50001");
            returnMap.put("msg", "验证码已发送!");
            return returnMap;
        }
        returnMap.put("errorcode", "0");
        returnMap.put("msg", "验证码已发送!");
        return returnMap;
    }

    // 绑定邮箱orPhone
    @OAuthRequired
    @RequestMapping(value = "/wechat/hunter/bindeEmail.do", method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> bindedEmail(HttpServletRequest request, ModelMap model,
                                    Hunter dto) {
        Map<String, Object> returnMap = new HashMap<String, Object>();

        HttpSession session = request.getSession();

        String openId = (String) session.getAttribute("OpenId");
        if (!StringUtils.hasText(openId)) {
            returnMap.put("errorcode", "40001");
            returnMap.put("msg", "必须在微信平台使用我们的服务");

            return returnMap;
        }
        if (dto == null || dto.getSecureCode() == null) {// || dto.getPhone() ==
            // null
            returnMap.put("errorcode", "40001");
            returnMap.put("msg", "提交参数有错");
            return returnMap;
        }

        Hunter hunter = hunterDAO.getByOpenId(openId);

        if (hunter == null) {

            logger.error("failed to save the hunter " + dto);
            returnMap.put("errorcode", "40001");
            returnMap.put("msg", "系统错误,你可能没关注我们公众号");

            return returnMap;
        } else {
            // validate the secure code
            String inputCode = dto.getSecureCode();

            String secureCode = hunter.getSecureCode();
            if (inputCode == null || secureCode == null) {
                logger.error("failed to save the hunter " + dto);
                returnMap.put("errorcode", "40001");
                returnMap.put("msg", "系统错误,请重新申请验证码");

                return returnMap;
            }
            if (inputCode.equalsIgnoreCase(secureCode)) {
                // equals binded
                hunter.setPhone(dto.getPhone());
                hunter.setEmail(dto.getEmail());
                // hunter.setBinded(1);
                hunter.setActive(1);
                logger.info("update hunter " + hunter);
                long hunterId = hunterDAO.update(hunter);
                if (hunterId >= 0) {
                    logger.info("successfully updated the hunter " + hunterId);
                    returnMap.put("errorcode", "0");
                    returnMap.put("msg", "成功保存猎头信息");
                    returnMap.put("data", dto);
                } else {
                    logger.error("failed to save the hunter " + dto);
                    returnMap.put("errorcode", "50001");
                    returnMap.put("msg", "验证失败,注册信息有误");
                }
                return returnMap;
            }
            // not equals return
            logger.error("secureCode is not correct： " + dto.getSecureCode());
            returnMap.put("errorcode", "40001");
            returnMap.put("msg", "创建猎头信息失败，请填写正确的验证码");
            return returnMap;
        }
    }

    // 绑定邮箱orPhone
    @OAuthRequired
    @RequestMapping(value = "/wechat/hunter/bindePhone.do", method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> bindedPhone(HttpServletRequest request, ModelMap model,
                                    Hunter dto) {
        Map<String, Object> returnMap = new HashMap<String, Object>();

        HttpSession session = request.getSession();

        String openId = (String) session.getAttribute("OpenId");
        if (!StringUtils.hasText(openId)) {
            returnMap.put("errorcode", "40001");
            returnMap.put("msg", "必须在微信平台使用我们的服务");

            return returnMap;
        }
        if (dto == null || dto.getSecureCode() == null
                || dto.getPhone() == null) {
            returnMap.put("errorcode", "40001");
            returnMap.put("msg", "提交参数有错");
            return returnMap;
        }

        Hunter hunter = hunterDAO.getByPhoneandOpenId(dto.getPhone(), openId);

        if (hunter == null) {

            logger.error("failed to save the hunter " + dto);
            returnMap.put("errorcode", "40001");
            returnMap.put("msg", "系统错误,你可能没关注我们公众号");

            return returnMap;
        } else {
            // validate the secure code
            String inputCode = dto.getSecureCode();

            String secureCode = hunter.getSecureCode();
            if (inputCode == null || secureCode == null) {
                logger.error("failed to save the hunter " + dto);
                returnMap.put("errorcode", "40001");
                returnMap.put("msg", "系统错误,请重新申请验证码");

                return returnMap;
            }
            if (inputCode.equalsIgnoreCase(secureCode)) {
                // equals binded
                hunter.setActive(1);
                hunter.setPhone(dto.getPhone());
                hunter.setEmail(dto.getEmail());
                // hunter.setState(Hunter.State.binded.toString());
                logger.info("update hunter " + hunter);
                long hunterId = hunterDAO.bindedPhone(hunter);
                if (hunterId >= 0) {
                    logger.info("successfully updated the hunter " + hunterId);
                    returnMap.put("errorcode", "0");
                    returnMap.put("msg", "成功保存猎头信息");
                    returnMap.put("data", dto);
                } else {
                    logger.error("failed to save the hunter " + dto);
                    returnMap.put("errorcode", "50001");
                    returnMap.put("msg", "验证失败,注册信息有误");
                }
                return returnMap;
            }
            // not equals return
            logger.error("secureCode is not correct： " + dto.getSecureCode());
            returnMap.put("errorcode", "40001");
            returnMap.put("msg", "创建猎头信息失败，请填写正确的验证码");
            return returnMap;
        }
    }

    // 创建猎头信息
    @OAuthRequired
    @RequestMapping(value = "wechat/hunter/create.do", method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> persistentHunter(HttpServletRequest request,
                                         ModelMap model, Hunter dto) throws Exception {
        Map<String, Object> returnMap = new HashMap<String, Object>();

        HttpSession session = request.getSession();

        String openId = (String) session.getAttribute("OpenId");
        if (!StringUtils.hasText(openId)) {
            returnMap.put("errorcode", "40001");
            returnMap.put("msg", "必须在微信平台使用我们的服务");
            return returnMap;
        }
        if (dto == null || dto.getName() == null || dto.getPhone() == null) {
            returnMap.put("errorcode", "40001");
            returnMap.put("msg", "提交参数有错");
            return returnMap;
        }

        Hunter hunter = hunterDAO.getByOpenId(openId);
        UserInfo user = userDAO.getByOpenId(openId);
        String headImg = "";
        if (user != null) {
            headImg = user.getHeadimgurl();
        }
        if (hunter == null) {
            // 创建新的hunter
            dto.setOpenid(openId);
            dto.setIcon(headImg);
            // // 0 没有绑定
            dto.setBinded(0);
            dto.setActive(Hunter.activate);
            Date now = new Date();
            dto.setCreateDate(now.getTime());
            int id = hunterDAO.save(dto);
            dto.setId(id);
            if (id > 0) {
                logger.info("successfully saved the hunter " + id);
                returnMap.put("errorcode", "0");
                returnMap.put("msg", "成功创建了猎头信息");
                returnMap.put("data", dto);
                //发送短信 给客服
                String content = String.format("有新的猎头（%s）更新了信息，请及时验证处理！", hunter.getName() );
                msgService.toSendMsgToService(content);
            } else {
                logger.error("failed to save the hunter " + dto);
                returnMap.put("errorcode", "50001");
                returnMap.put("msg", "创建猎头信息失败，可能您的信息已经注册为猎头了，请联系管理员");
            }
            return returnMap;
        } else {
            // 编辑更新
//            hunter.setHeadImgUrl(headImg);
            hunter.setName(dto.getName());
            hunter.setEnglishname(dto.getEnglishname());
            hunter.setIdnumber(dto.getIdnumber());
            hunter.setCityId(dto.getCityId());
            City city = cityDAO.getById(dto.getCityId());
            hunter.setCityName(city.getName());
            hunter.setWorkage(dto.getWorkage());
            Domain domain = domainDAO.getById(dto.getMajordomain1());
            hunter.setMajordomain1(dto.getMajordomain1());
            hunter.setDomainName1(domain.getName());
            domain = domainDAO.getById(dto.getMajordomain2());
            hunter.setMajordomain2(dto.getMajordomain2());
            hunter.setDomainName2(domain.getName());
            domain = domainDAO.getById(dto.getMajordomain3());
            hunter.setMajordomain3(dto.getMajordomain3());
            hunter.setDomainName3(domain.getName());
            // hunter.setMajordomain2(dto.getMajordomain2());
            // hunter.setMajordomain3(dto.getMajordomain3());
            hunter.setComment(dto.getComment());
            hunter.setCreateDate(System.currentTimeMillis());
            hunter.setAdvantage(dto.getAdvantage());
            hunter.setEmail(dto.getEmail());
            if (dto.getPhone() != null) {
                hunter.setState(Hunter.State.approved.toString());
                hunter.setBinded(0);
            } else {
                hunter.setBinded(0);
            }
            hunter.setBestdomain(dto.getBestdomain());
            hunter.setServiceTags(dto.getServiceTags());
            hunter.setRoleIds(dto.getRoleIds());
            logger.info("update hunter " + hunter);
            int count = hunterDAO.updateProfile(hunter);

            if (count > 0) {

                logger.info("successfully updated the hunter " + hunter.getId());
                returnMap.put("errorcode", "0");
                returnMap.put("msg", "成功保存猎头信息");
                returnMap.put("data", dto);
                //发送短信 给客服
                String content = String.format("猎头%s更新了个人认证信息，请及时审核", hunter.getName() );
                msgService.toSendMsgToService(content);
            } else {
                logger.error("failed to save the hunter " + dto);
                returnMap.put("errorcode", "50001");
                returnMap.put("msg", "更新猎头信息出错");
            }
            orderDescDAO.deleteAllByHunterId(hunter.getId());
            orderDescDAO.batchSave(hunter.getId(), dto.getOrderDesc(), 1, currentTime(), currentTime());
            return returnMap;
        }
    }




    // 显示编辑猎头信息
    @OAuthRequired
    @RequestMapping(value = "wechat/hunter/toEdit.page", method = RequestMethod.GET)
    public String toEditHunterProfile(HttpServletRequest request, int hunterId,
                                      Model model) {

        HttpSession session = request.getSession();

        String openId = (String) session.getAttribute("OpenId");
        logger.debug("openid is " + openId);
        if (!StringUtils.hasText(openId)) {
            logger.info("empty openid ,wexin browser is needed.");
            return "wechat/headhunter/errorpage";
        }
        Hunter hunter = hunterDAO.getByOpenId(openId);
        if (hunter == null) {
            return "wechat/headhunter/errorpage";
        }

        model.addAttribute("hunter", hunter);
        List<Domain> domains = domainDAO.getAllSubDomain();
        model.addAttribute("domains", domains);
        List<City> cities = cityDAO.getALL();
        model.addAttribute("cities", cities);

        /* */
        String ticket = sysConfigService.getJsTicket();
        logger.debug("js api ticket is " + ticket);
        String url = request.getRequestURL().toString();
        if (!StringUtils.isEmpty(request.getQueryString())) {
            url = url + "?" + request.getQueryString();
        }
        url = url.replace("http", "https");
        logger.debug("request url is " + url);

        Map<String, String> jsconfig = SignUtil.getJSSignature(ticket, url);

        jsConfig config = new jsConfig();
        config.setAppid(WebchatServiceConstant.APPID);
        config.setCurrenttimestamp(jsconfig.get("timestamp"));
        config.setNonceStr(jsconfig.get("nonceStr"));
        config.setSignatureStr(jsconfig.get("signature"));
        model.addAttribute("config", config);
        List<OrderDesc> orderDescList = orderDescDAO.listAll();
        model.addAttribute("orderDesc", orderDescList);
        List<OrderDesc> orderDescOwner = orderDescDAO.getAllByHunterId(hunterId);
        List<Long> orderDescOwnerIds = orderDescOwner.stream().map(OrderDesc::getId).collect(Collectors.toList());
        model.addAttribute("orderDescOwner", orderDescOwnerIds);
        return "wechat/headhunter/hunter/lietouxinxi1";
    }

    @OAuthRequired
    @RequestMapping(value = "wechat/hunter/toUploadFile.page", method = RequestMethod.GET)
    public String toUploadFile(HttpServletRequest request, Model model) {
        HttpSession session = request.getSession();

        String openid = (String) session.getAttribute("OpenId");
        //String openid = "o852Is8GrZljbUUF3gXc4lgEKhyg";

        logger.debug("openid is " + openid);
        if (!StringUtils.hasText(openid)) {
            logger.info("empty openid ,wexin browser is needed.");
            return "wechat/headhunter/errorpage";
        }

        Hunter hunter = hunterDAO.getByActivateHunter(openid);
        if (hunter == null) {
            return "wechat/headhunter/errorpage";
        }
        model.addAttribute("hunter", hunter);
        // int companyId = hunter.getCompanyId();
        // HunterCompany company = hunterCompanyDAO.getById(companyId);
        // if(company==null)
        // {
        // logger.error("the input parameter is not correct");
        // model.addAttribute("message", "the input parameter about the hunter
        // is not correct");
        // return "wechat/headhunter/errorpage";
        // }

        // JSTicket ticket = JSTicketAPI.getJsTicket(token.getAccess_token());
        String ticket = sysConfigService.getJsTicket();
        logger.debug("js api ticket is " + ticket);
        String url = request.getRequestURL().toString();
        if (!StringUtils.isEmpty(request.getQueryString())) {
            url = url + "?" + request.getQueryString();
        }
        logger.debug("request url is " + url);

        Map<String, String> jsconfig = SignUtil.getJSSignature(ticket, url);

        jsConfig config = new jsConfig();
        config.setAppid(WebchatServiceConstant.APPID);
        config.setCurrenttimestamp(jsconfig.get("timestamp"));
        config.setNonceStr(jsconfig.get("nonceStr"));
        config.setSignatureStr(jsconfig.get("signature"));

        model.addAttribute("config", config);

        // String image = company.getImageUrl();
        //
        // if(StringUtils.hasText(image))
        // {
        // return "wechat/headhunter/hunter/lietouxinxi4";
        // }
        // model.addAttribute("company", company);

        return "wechat/headhunter/hunter/lietouxinxi3";
    }

    /*
     * //@OAuthRequired
     *
     * @RequestMapping(value = "wechat/hunter/toView.page", method =
     * RequestMethod.GET) public String toViewHunter(HttpServletRequest request,
     * int hunterId, int companyId, Model model) { Hunter hunter =
     * hunterDAO.getById(hunterId); model.addAttribute("hunter", hunter);
     * HunterCompany company = hunterCompanyDAO.getById(companyId);
     * model.addAttribute("company", company); return
     * "wechat/headhunter/hunter/lietouxinxi"; }
     */
    @OAuthRequired
    @RequestMapping(value = "wechat/hunter/uploadFile.do", method = RequestMethod.POST)
    public String uploadFile(HttpServletRequest request, MultipartFile file,
                             Model model) {

        HttpSession session = request.getSession();
        String openId = (String) session.getAttribute("OpenId");

        //String openId ="o852Is8GrZljbUUF3gXc4lgEKhyg";
        if (!StringUtils.hasText(openId)) {
            logger.info("session过期,请关闭重试");
            return "wechat/headhunter/errorPage";
        }
        Hunter hunter = hunterDAO.getByActivateHunter(openId);
        if (hunter == null) {
            return "wechat/headhunter/errorpage";
        }
        // String realPath =
        // request.getSession().getServletContext().getRealPath("/resources/images/huntercompany");
        if (!file.isEmpty()) {
            String realPath = FileController.BASE_PATH;
            logger.debug("path is " + realPath);
            //创建文件
            File dir = new File(realPath);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            String id = currentDate();
            String fileName = file.getOriginalFilename();
            String img = id + fileName.substring(fileName.lastIndexOf("."));//zhao.jpg
            String filePathName = realPath + img;
            FileOutputStream imgOut;
            try {
                imgOut = new FileOutputStream(new File(dir, img));//根据 dir 抽象路径名和 img 路径名字符串创建一个新 File 实例。
                imgOut.write(file.getBytes());//返回一个字节数组文件的内容
                imgOut.close();
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            // 缩略图begin
            String thumbnailPathName = id + "small."
                    + FilenameUtils.getExtension(file.getOriginalFilename());
            //added by yangkang 2016-3-30 去掉后缀中包含的.png字符串
            if (thumbnailPathName.contains(".png")) {
                thumbnailPathName = thumbnailPathName.replace(".png", ".jpg");
            }
            long size = file.getSize();
            double scale = 1.0d;
            if (size >= 200 * 1024) {
                if (size > 0) {
                    scale = (200 * 1024f) / size;
                }
            }

            //拼接文件路劲
            String thumbnailFilePathName = realPath + thumbnailPathName;
            try {
                if (size < 200 * 1024) {
                    Thumbnails.of(filePathName).scale(1f).outputFormat("jpg").toFile(thumbnailFilePathName);
                } else {
                    Thumbnails.of(filePathName).scale(1f).outputQuality(scale).outputFormat("jpg").toFile(thumbnailFilePathName);
                }

            } catch (Exception e1) {
                return e1.getMessage();
            }
            //删除原文件
            if (filePathName != null) {
                new File(filePathName).delete();
            }

            //String token = sysConfigService.getAccessToken();

            logger.debug("getMedia()");

            hunter.setImageUrl(thumbnailPathName);
            hunterDAO.updateImage(hunter);
        }
//		Map<String, Object> result = MediaAPI.getMediaFromWechat(realPath,
//				resId, token);

        /* */
        String ticket = sysConfigService.getJsTicket();
        logger.debug("js api ticket is " + ticket);
        String url = request.getRequestURL().toString();
        if (!StringUtils.isEmpty(request.getQueryString())) {
            url = url + "?" + request.getQueryString();
        }
        url = url.replace("http", "https");
        logger.debug("request url is " + url);

        Map<String, String> jsconfig = SignUtil.getJSSignature(ticket, url);

        jsConfig config = new jsConfig();
        config.setAppid(WebchatServiceConstant.APPID);
        config.setCurrenttimestamp(jsconfig.get("timestamp"));
        config.setNonceStr(jsconfig.get("nonceStr"));
        config.setSignatureStr(jsconfig.get("signature"));

        model.addAttribute("config", config);
        /* */

        //send sms Lin
        try {
            SMSService.sendCheckSMS(hunter.getPhone(), "顾问猎头");
        } catch (Exception e) {
            e.printStackTrace();
        }

        //send msg headoffer Lin
        String tempjsonemployer = TemplateData
                .New()
                .setTouser(WebchatServiceConstant.SENDSMSLIN)
                .setTemplate_id("POheDTxtThQUaqzoDVt__a7GaHY4GP4nt4v7HB4OCG4")
                .setUrl("https://www.headoffer.com/hrplus")
                .add("first",
                        "您好，用户" + hunter.getPhone() + "已经提交认证信息，请审核", "#274084")
                .add("keyword1", hunter.getPhone(), "#000000")
                .add("keyword2", "顾问猎头认证", "#F47e2d")
                .add("keyword3", "待审核", "#000000")
                .add("keyword4", DateUtils.getDate(), "#000000")
                .add("remark", "如非您本人操作请联系平台客服咨询，点击查看订单详情。", "#000000")
                .build();
        System.out.println(tempjsonemployer);
        ApiResult resulthunters = TemplateMsgApi.send(tempjsonemployer);
        logger.info("headoffer review check ，send msg result=" + resulthunters);


        return "wechat/headhunter/hunter/lietouxinxi4";
    }

    // 订单信息0待接单，1进行中，2维权中，3已完成，4已取消，5已拒单
    @OAuthRequired
    @RequestMapping(value = "wechat/hunter/orderList.page")
    public String orderList(HttpServletRequest request, Model model) {
        HttpSession session = request.getSession();

        String openId = (String) session.getAttribute("OpenId");
        // String openId = "o852IszDHWj5PUFrZyNiI6o9_LbU";
        // String openId = "o852Is8GrZljbUUF3gXc4lgEKhyg";
        logger.debug("openid is " + openId);
        if (!StringUtils.hasText(openId)) {
            logger.info("empty openid ,wexin browser is needed.");
            return "wechat/headhunter/errorpage";
        }
        Hunter hunter = hunterDAO.getByOpenId(openId);
        if (hunter == null) {
            model.addAttribute("title", "温馨提示");
            model.addAttribute("msg", "你尚未注册我们的平台，请点击下方按钮前往注册。");
            model.addAttribute("url", "wechat/hunter/main.page");
            return "wechat/headhunter/msgpage";
        } else {
            if (hunter.getBinded() != 1) {
                model.addAttribute("title", "信息审核中");
                model.addAttribute("msg", "您的信息正在认证审核中，审核通过后会有短信通知您，请您耐心等待。如有疑问请添加我们的客服微信（ID:ElenaYu807）咨询。");
                return "wechat/headhunter/msgpage";
            }
            //全部
            List<Order> allorder = orderDAO.getAllOrdersByHunterId(hunter.getId());
            for (Order ord : allorder) {
                OrderDesc or = orderDescDAO.getById(ord.getOrdescId());
                ord.setOrderdesc("￥" + or.getSpec() + "/" + or.getName());
                if (ord.getStatus() == 0) {
                    ord.setStatusName("待接单");
                } else if (ord.getStatus() == 1) {
                    ord.setStatusName("进行中");
                } else if (ord.getStatus() == 2) {
                    ord.setStatusName("维权中");
                } else if (ord.getStatus() == 3) {
                    ord.setStatusName("已完成");
                } else if (ord.getStatus() == 4) {
                    ord.setStatusName("已取消");
                } else if (ord.getStatus() == 5) {
                    ord.setStatusName("已拒单");
                } else if (ord.getStatus() == 6) {
                    ord.setStatusName("已评价");
                } else if (ord.getStatus() == 7) {
                    ord.setStatusName("顾问确认完成，待用户确认！");
                }
            }

            // 待接单
            List<Order> order = orderDAO.getUNOrdersByHunterId(hunter.getId());
            for (Order ord : order) {
                OrderDesc or = orderDescDAO.getById(ord.getOrdescId());
                ord.setOrderdesc("￥" + or.getSpec() + "/" + or.getName());
                if (ord.getStatus() == 0) {
                    ord.setStatusName("待接单");
                }
            }
            // 进行中
            List<Order> ordering = orderDAO.getOrdersingByHunterId(hunter.getId());
            for (Order ord : ordering) {
                OrderDesc or = orderDescDAO.getById(ord.getOrdescId());
                ord.setOrderdesc("￥" + or.getSpec() + "/" + or.getName());
                if (ord.getStatus() == 1) {
                    ord.setStatusName("进行中");
                }
            }
            // 已完成
            List<Order> ordered = orderDAO.getOrdersedByHunterId(hunter.getId());
            for (Order ord : ordered) {
                OrderDesc or = orderDescDAO.getById(ord.getOrdescId());
                ord.setOrderdesc("￥" + or.getSpec() + "/" + or.getName());
                if (ord.getStatus() == 3) {
                    ord.setStatusName("已完成");
                } else if (ord.getStatus() == 4) {
                    ord.setStatusName("已取消");
                } else if (ord.getStatus() == 5) {
                    ord.setStatusName("已拒单");
                } else if (ord.getStatus() == 6) {
                    ord.setStatusName("已评价");
                } else if (ord.getStatus() == 7) {
                    ord.setStatusName("顾问确认完成，待用户确认！");
                }
            }
            // 已评价
            List<Evaluate> evalist = evaluateDAO.getEvaByHunterId(hunter.getId());
            for (Evaluate evaluate : evalist) {
                Order or = orderDAO
                        .getById(Integer.parseInt(evaluate.getOrderId()));
                evaluate.setOrderCode(or.getOrdercode());
            }
            model.addAttribute("allorders", allorder);
            model.addAttribute("unorderlist", order);
            model.addAttribute("orderinglist", ordering);
            model.addAttribute("orderedlist", ordered);
            model.addAttribute("evalist", evalist);
            model.addAttribute("hunter", hunter);
            List<Domain> domains = domainDAO.getAllSubDomain();
            model.addAttribute("domains", domains);
            List<City> cities = cityDAO.getALL();
            model.addAttribute("cities", cities);

            /* */
            String ticket = sysConfigService.getJsTicket();
            logger.debug("js api ticket is " + ticket);
            String url = request.getRequestURL().toString();
            if (!StringUtils.isEmpty(request.getQueryString())) {
                url = url + "?" + request.getQueryString();
            }
            url = url.replace("http", "https");
            logger.debug("request url is " + url);

            Map<String, String> jsconfig = SignUtil.getJSSignature(ticket, url);

            jsConfig config = new jsConfig();
            config.setAppid(WebchatServiceConstant.APPID);
            config.setCurrenttimestamp(jsconfig.get("timestamp"));
            config.setNonceStr(jsconfig.get("nonceStr"));
            config.setSignatureStr(jsconfig.get("signature"));

            model.addAttribute("config", config);
            /* */
            /* */
            return "wechat/headhunter/hunter/orderlist";
        }
    }

    /**
     * 订单详细信息
     *
     * @param request
     * @param model
     * @param orderId
     * @return
     */
    @OAuthRequired
    @RequestMapping(value = "wechat/hunter/toOrderDetail.do", method = RequestMethod.GET)
    public String orderDetail(HttpServletRequest request, Model model,
                              int orderId) {
        HttpSession session = request.getSession();

        String openId = (String) session.getAttribute("OpenId");
        //String openId="o852Is7ih5u1jnXnLaRixmqWn9zk";
        logger.debug("openid is " + openId);
        if (!StringUtils.hasText(openId)) {
            logger.info("empty openid ,wexin browser is needed.");
            return "wechat/headhunter/errorpage";
        }
        Hunter hunter = hunterDAO.getByOpenId(openId);
        if (hunter == null) {
            return "wechat/headhunter/errorpage";
        }
        // 0待接单，1进行中，2维权中，3已完成，4已取消，5已拒单
        Order order = orderDAO.getById(orderId);
        if (order != null) {
            OrderDesc desc = orderDescDAO.getById(order.getOrdescId());
            order.setOrderdesc("￥" + order.getPayMoney() / 100 + "/" + desc.getName());
            if (order.getStatus() == 0) {
                order.setStatusName("待接单");
            } else if (order.getStatus() == 1) {
                order.setStatusName("进行中");
            } else if (order.getStatus() == 3) {
                order.setStatusName("已完成");
            } else if (order.getStatus() == 4) {
                order.setStatusName("已取消");
            } else if (order.getStatus() == 5) {
                order.setStatusName("已拒单");
            } else if (order.getStatus() == 6) {
                order.setStatusName("已评价");
            } else if (order.getStatus() == 7) {
                order.setStatusName("顾问确认完成，待用户确认！");
            }
            model.addAttribute("order", order);
            // 我的评价
            Evaluate eva = evaluateDAO.getEvaByOrderId(String.valueOf(orderId));
            model.addAttribute("eva", eva);
            // 我的联系人
            //WxAppUser appUser = wxAppUserDAO.getByOpenId(order.getOpenid());
            Employee appUser = employeeDAO.getByEmpId(order.getEmployeeId());
            model.addAttribute("appUser", appUser);

        }
        /* */
        String ticket = sysConfigService.getJsTicket();
        logger.debug("js api ticket is " + ticket);
        String url = request.getRequestURL().toString();
        if (!StringUtils.isEmpty(request.getQueryString())) {
            url = url + "?" + request.getQueryString();
        }
        url = url.replace("http", "https");
        logger.debug("request url is " + url);

        Map<String, String> jsconfig = SignUtil.getJSSignature(ticket, url);

        jsConfig config = new jsConfig();
        config.setAppid(WebchatServiceConstant.APPID);
        config.setCurrenttimestamp(jsconfig.get("timestamp"));
        config.setNonceStr(jsconfig.get("nonceStr"));
        config.setSignatureStr(jsconfig.get("signature"));

        model.addAttribute("config", config);
        OrderDesc orderDesc = orderDescDAO.getById(order.getOrdescId());
        model.addAttribute("orderDesc", orderDesc);
        /* */

        return "wechat/headhunter/hunter/orderxiangxixinxi";
    }

    /**
     * 候选人详细信息
     *
     * @param request
     * @param model
     * @param mobile
     * @return
     */
    @OAuthRequired
    @RequestMapping(value = "wechat/hunter/toViewCandidate.do", method = RequestMethod.GET)
    public String toViewCandidate(HttpServletRequest request, Model model,
                                  String mobile) {
        EmployeePerson emp = employeeDAO.existPhone(mobile);
        model.addAttribute("employee", emp);
        int domainId = domainDAO.getRootDomainId(emp.getDomainId());
        logger.info("toViewCandidate domain id =" + domainId);
        model.addAttribute("domainId", domainId);
        /* */
        String ticket = sysConfigService.getJsTicket();
        logger.debug("js api ticket is " + ticket);
        String url = request.getRequestURL().toString();
        if (!StringUtils.isEmpty(request.getQueryString())) {
            url = url + "?" + request.getQueryString();
        }
        url = url.replace("http", "https");
        logger.debug("request url is " + url);

        Map<String, String> jsconfig = SignUtil.getJSSignature(ticket, url);

        jsConfig config = new jsConfig();
        config.setAppid(WebchatServiceConstant.APPID);
        config.setCurrenttimestamp(jsconfig.get("timestamp"));
        config.setNonceStr(jsconfig.get("nonceStr"));
        config.setSignatureStr(jsconfig.get("signature"));

        model.addAttribute("config", config);
        /* */

        return "wechat/headhunter/hunter/zhitongche";
    }

    // 修改订单状态信息
    @OAuthRequired
    @RequestMapping(value = "wechat/hunter/updOrder.do", method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> updOrder(HttpServletRequest request, ModelMap model,
                                 int orderId, int status) {
        Map<String, Object> returnMap = new HashMap<String, Object>();

        HttpSession session = request.getSession();

        String openId = (String) session.getAttribute("OpenId");
        //String openId="o852Is7ih5u1jnXnLaRixmqWn9zk";
        if (!StringUtils.hasText(openId)) {
            returnMap.put("errorcode", "40001");
            returnMap.put("msg", "必须在微信平台使用我们的服务");
            return returnMap;
        }
        // 编辑更新
        int res = orderDAO.updateStatus(status, orderId);
        Order order = orderDAO.getById(orderId);
        OrderDesc desc = orderDescDAO.getById(order.getOrdescId());
        Hunter hunter = hunterDAO.getById(order.getHunterId());
        Employee employee = employeeDAO.getByEmpId(order.getEmployeeId());
        Person person = null;
        UserInfo userinfo = null;
        if (employee != null) {
            System.out.println("update personid=" + employee.getPersonId());
            person = personDAO.getById(employee.getPersonId());
            userinfo = personDAO.getOpenidByUnionid(employee.getPersonId());
        }
        // 顾问接单前 客户没有填写信息标志位
        boolean contentFlag = checkCustomerSupplyInfo(orderId,desc);


        if (res > 0 && status == 1 && desc != null && order != null) {
            returnMap.put("errorcode", "0");
            returnMap.put("msg", "已接受该预约咨询服务！");
            // 推送msg于hunter
            String tempjson = TemplateData
                    .New()
                    .setTouser(openId)
                    .setTemplate_id(
                            "NRCvt7vthW-aNjQFAkHWA2GIQzpxCOC04VdyNA_7yMc")
                    .setUrl("https://www.tiaonali.com/tnl-hunter/wechat/hunter/toOrderDetail.do?orderId="
                            + orderId)
                    .add("first",
                            "您已接受用户的"+desc.getName()+"咨询预约订单", "#274084")
                    .add("keyword1", "YQS" + order.getOrdercode(), "#000000")
                    .add("keyword2", "进行中", "#F47e2d")
                    .add("keyword3", currentTime(), "#000000")
                    .add("remark", "点击查看订单详情，请您在预约时间，注意接听用户来电，谢谢！", "#000000")
                    .build();
            ApiResult result = TemplateMsgApi.send(tempjson);
            System.out.println(result);
            if(contentFlag){
                try {
                    String content = hunter.getName() + "顾问您好，用户已补充咨询相关资料，您可至公众号[headoffer会猎]中查看。并请您在预约时间，注意接听用户来电，谢谢！";
                    SMSService.sendSMSTakerOrder(hunter.getPhone(), "https://www.tiaonali.com/tnl-candidate/wechat/order/toOrderDetail.do?orderId=" + orderId, content);
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }



            if (contentFlag){
                // 推送msg于candidate
                String tempYRCJson = TemplateData
                        .New()
                        .setTouser(person.getOpenid())
                        .setTemplate_id(
                                "TKaDuBl8hbYPVYrPcUBIk5LB3f1N422qxscC088xyIw")
                        .setUrl("https://www.tiaonali.com/tnl-candidate/wechat/order/toOrderDetail.do?orderId="
                                + orderId)
                        .setMiniprogram(WebchatServiceConstant.APPID_ZHIDAO, "/pages/my-ordetail/my-ordetail?orderId=" + orderId)
                        .add("first",
                                "您预约的" + desc.getName() + "咨询服务顾问已接单", "#274084")
                        .add("keyword1", "YQS" + order.getOrdercode(), "#000000")
                        .add("keyword2", "进行中", "#F47e2d")
                        .add("keyword3", currentTime(), "#000000")
                        .add("remark", "请提前至[职道]小程序[个人中心]-[我的咨询]-[进行中]订单获取顾问电话，并在预约时间内拨打咨询。如有问题，可咨询18721386781。", "#000000")
                        .build();
                ApiResult resultYRC = WxaTemplateUtil.sendtiaonalis(tempYRCJson);
                System.out.println(resultYRC);


                try {
                    String content = String.format("您预约的%s咨询服务顾问已接单，" +
                            "请提前至[职道]小程序[个人中心]-[我的咨询]-[进行中]订单获取顾问电话，并在预约时间内拨打咨询。如有问题，可咨询18721386781。", hunter.getName());
                    SMSService.sendSMSTakerOrder(employee.getPhone(), "https://www.tiaonali.com/tnl-candidate/wechat/order/toOrderDetail.do?orderId=" + orderId, content);
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }else{
                // 推送msg于candidate
                String tempYRCJson = TemplateData
                        .New()
                        .setTouser(person.getOpenid())
                        .setTemplate_id(
                                "TKaDuBl8hbYPVYrPcUBIk5LB3f1N422qxscC088xyIw")
                        .setUrl("https://www.tiaonali.com/tnl-candidate/wechat/order/toOrderDetail.do?orderId="
                                + orderId)
                        .setMiniprogram(WebchatServiceConstant.APPID_ZHIDAO, "/pages/my-ordetail/my-ordetail?orderId=" + orderId)
                        .add("first",
                                "您预约的" + desc.getName() + "咨询服务顾问已接单", "#274084")
                        .add("keyword1", "YQS" + order.getOrdercode(), "#000000")
                        .add("keyword2", "进行中", "#F47e2d")
                        .add("keyword3", currentTime(), "#000000")
                        .add("remark", "为了顾问能提前了解您的情况，您需点击详情完善咨询信息。如有问题，可咨询18721386781。", "#000000")
                        .build();
                ApiResult resultYRC = WxaTemplateUtil.sendtiaonalis(tempYRCJson);
                System.out.println(resultYRC);


                try {
                    String content = String.format("您预约的%s咨询服务顾问已接单，为了顾问能提前了解您的情况，您需完善咨询信息，前往[职道]小程序（个人中心-我的咨询-订单待接单详情页完善）。如有问题，可咨询18721386781。", desc.getName());
                    SMSService.sendSMSTakerOrder(employee.getPhone(), "https://www.tiaonali.com/tnl-candidate/wechat/order/toOrderDetail.do?orderId=" + orderId, content);
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }





        } else if (res > 0 && status == 5 && desc != null && order != null) {
            returnMap.put("errorcode", "0");
            returnMap.put("msg", "拒绝该预约咨询服务！");
            String tempjson = TemplateData
                    .New()
                    .setTouser(openId)
                    .setTemplate_id("NRCvt7vthW-aNjQFAkHWA2GIQzpxCOC04VdyNA_7yMc")
                    .setUrl("https://www.tiaonali.com/tnl-hunter/wechat/hunter/toOrderDetail.do?orderId="
                            + orderId)
                    .add("first",
                            "您好,您已拒绝" + person.getName() + "预约咨询。", "#274084")
                    .add("keyword1", "YQS" + order.getOrdercode(), "#000000")
                    .add("keyword2", "已拒单", "#F47e2d")
                    .add("keyword3", currentTime(), "#000000")
                    .add("remark", "如非您本人操作请联系平台客服咨询，点击查看订单详情。", "#000000")
                    .build();
            System.out.println(tempjson);
            ApiResult result = TemplateMsgApi.send(tempjson);
            System.out.println(result);

            // 推送msg于candidate
            String tempYRCJson = TemplateData
                    .New()
                    .setTouser(person.getOpenid())
                    .setTemplate_id(
                            "TKaDuBl8hbYPVYrPcUBIk5LB3f1N422qxscC088xyIw")
                    .setUrl("https://www.tiaonali.com/tnl-candidate/wechat/order/toOrderDetail.do?orderId="
                            + orderId)
                    .setMiniprogram(WebchatServiceConstant.APPID_ZHIDAO, "/pages/my-ordetail/my-ordetail?orderId=" + orderId)
                    .add("first",
                            "您好,您预约的" + hunter.getName() + "顾问的「" + "￥" + desc.getSpec() + "/"
                                    + desc.getName() + "」咨询项目,因顾问时间临时调整或其他原因，已被取消订单，您可以重新预约其他顾问。", "#274084")
                    .add("keyword1", "YQS" + order.getOrdercode(), "#000000")
                    .add("keyword2", "已拒单", "#F47e2d")
                    .add("keyword3", currentTime(), "#000000")
                    .add("remark", "如非本人操作，请联系平台客服咨询，点击查看订单详情", "#000000")
                    .build();
            ApiResult resultYRC = WxaTemplateUtil.sendtiaonalis(tempYRCJson);
            System.out.println(resultYRC);
            try {
                SMSService.sendSMSrefuseOrder(employee.getPhone(), hunter.getName(), "￥" + desc.getSpec() + "/"
                        + desc.getName());
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        } else if (res > 0 && status == 7 && desc != null && order != null) {
            returnMap.put("errorcode", "0");
            returnMap.put("msg", "已确认完成预约咨询服务，待候选人确认完成！");
            String tempjson = TemplateData
                    .New()
                    .setTouser(openId)
                    .setTemplate_id(
                            "NRCvt7vthW-aNjQFAkHWA2GIQzpxCOC04VdyNA_7yMc")
                    .setUrl("https://www.tiaonali.com/tnl-hunter/wechat/hunter/toOrderDetail.do?orderId="
                            + orderId)
                    .add("first",
                            "您好,您已确认完成" + person.getName() + "预约咨询，待候选人确认完成！", "#274084")
                    .add("keyword1", "YQS" + order.getOrdercode(), "#000000")
                    .add("keyword2", "确认完成", "#F47e2d")
                    .add("keyword3", currentTime(), "#000000")
                    .add("remark", "如非您本人操作请联系平台客服咨询，点击查看订单详情。", "#000000")
                    .build();
            System.out.println(tempjson);
            ApiResult result = TemplateMsgApi.send(tempjson);
            System.out.println(result);
            // 推送msg于candidate
            String tempYRCJson = TemplateData
                    .New()
                    .setTouser(person.getOpenid())
                    .setTemplate_id(
                            "TKaDuBl8hbYPVYrPcUBIk5LB3f1N422qxscC088xyIw")
                    .setUrl("https://www.tiaonali.com/tnl-candidate/wechat/order/toOrderDetail.do?orderId="
                            + orderId)
                    .setMiniprogram(WebchatServiceConstant.APPID_ZHIDAO, "/pages/my-ordetail/my-ordetail?orderId=" + orderId)
                    .add("first",
                            "您好,您预约的" + hunter.getName() + "顾问的「" + "￥" + desc.getSpec() + "/"
                                    + desc.getName() + "」咨询项目顾问确认已完成，待您确认完成，非常感谢。", "#274084")
                    .add("keyword1", "YQS" + order.getOrdercode(), "#000000")
                    .add("keyword2", "待确认完成", "#F47e2d")
                    .add("keyword3", currentTime(), "#000000")
                    .add("remark", "如非本人操作，请联系平台客服咨询，点击查看订单详情", "#000000")
                    .build();
            ApiResult resultYRC = WxaTemplateUtil.sendtiaonalis(tempYRCJson);
            System.out.println(resultYRC);
            try {
                SMSService.sendSMSconfirmOrder(employee.getPhone(), hunter.getName());
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        } else {
            returnMap.put("errorcode", "50001");
            returnMap.put("msg", "接受预约咨询信息出错");
        }
        return returnMap;
    }

    private boolean checkCustomerSupplyInfo(Integer orderId, OrderDesc desc) {
        if (desc.getTag().indexOf("简历修改") != -1){
            OrderResume resume = orderResumeDAO.getByOrderId(orderId);
            return resume != null && !StringUtils.isEmpty(resume.getFile());
        }
        if (desc.getTag().indexOf("面试辅导") != -1){
            OrderInterview interview = interviewDAO.getInterviewByOrderId(orderId);
            return interview != null && !StringUtils.isEmpty(interview.getFile());
        }

        if (desc.getTag().indexOf("薪酬分析") != -1){
            OrderSalary salary = salaryDAO.getByOrderId(orderId);
            return salary != null;
        }

        if (desc.getTag().indexOf("职业规划") != -1){
            OrderPlan orderPlan = planDAO.getPlanByOrderId(orderId);
            return orderPlan != null;
        }


        if (desc.getTag().indexOf("离职咨询") != -1){
            OrderLeave orderLeave = leaveDAO.getLeaveByOrderId(orderId);
            return orderLeave != null;
        }

        return false;
    }

    // 服务设置
    @OAuthRequired
    @RequestMapping(value = "wechat/hunter/descList.page")
    public String orderDescList(HttpServletRequest request, Model model) {
        HttpSession session = request.getSession();

        String openId = (String) session.getAttribute("OpenId");
        //String openId="o852Is7ih5u1jnXnLaRixmqWn9zk";
        logger.debug("openid is " + openId);
        if (!StringUtils.hasText(openId)) {
            logger.info("empty openid ,wexin browser is needed.");
            return "wechat/headhunter/errorpage";
        }
        Hunter hunter = hunterDAO.getByOpenId(openId);
        if (hunter == null) {
            model.addAttribute("title", "温馨提示");
            model.addAttribute("msg", "你尚未注册我们的平台，请点击下方按钮前往注册。");
            model.addAttribute("url", "wechat/hunter/main.page");
            return "wechat/headhunter/msgpage";
        } else {
            if (hunter.getBinded() != 1) {
                model.addAttribute("title", "信息审核中");
                model.addAttribute("msg", "您的信息正在认证审核中，审核通过后会有短信通知您，请您耐心等待。如有疑问请添加我们的客服微信（ID:ElenaYu807）咨询。");
                return "wechat/headhunter/msgpage";
            }
            List<OrderDesc> descs = orderDescDAO.getAllByHunterId(hunter.getId());
            model.addAttribute("desclist", descs);
            return "wechat/headhunter/hunter/desclist";
        }
    }

    // 显示编辑服务设置信息
    @OAuthRequired
    @RequestMapping(value = "wechat/hunter/toCreateDesc.page", method = RequestMethod.GET)
    public String toCreateDesc(HttpServletRequest request, Model model) {
        HttpSession session = request.getSession();
        String openId = (String) session.getAttribute("OpenId");
        System.out.println(openId);
//		String openId = "o852Is75Z4x8xnGEKVzAYB-JDwFA";
        logger.debug("openid is " + openId);
        if (!StringUtils.hasText(openId)) {
            logger.info("empty openid ,wexin browser is needed.");
            return "wechat/headhunter/errorpage";
        }
        Hunter hunter = hunterDAO.getByOpenId(openId);
        if (hunter == null) {
            model.addAttribute("title", "温馨提示");
            model.addAttribute("msg", "你尚未注册我们的平台，请点击下方按钮前往注册。");
            model.addAttribute("url", "wechat/hunter/main.page");
            return "wechat/headhunter/msgpage";
        }
        /* */

        return "wechat/headhunter/hunter/descForm";
    }

    // 显示编辑服务设置信息
    @OAuthRequired
    @RequestMapping(value = "wechat/hunter/toEditDesc.page", method = RequestMethod.GET)
    public String toEditHunterDesc(HttpServletRequest request, int ordescId, Model model) {
        HttpSession session = request.getSession();
        String openId = (String) session.getAttribute("OpenId");
        logger.debug("openid is " + openId);
        if (!StringUtils.hasText(openId)) {
            logger.info("empty openid ,wexin browser is needed.");
            return "wechat/headhunter/errorpage";
        }
        Hunter hunter = hunterDAO.getByOpenId(openId);
        if (hunter == null) {
            model.addAttribute("title", "温馨提示");
            model.addAttribute("msg", "你尚未注册我们的平台，请点击下方按钮前往注册。");
            model.addAttribute("url", "wechat/hunter/main.page");
            return "wechat/headhunter/msgpage";
        } else {
            OrderDesc orderdesc = orderDescDAO.getById(ordescId);
            model.addAttribute("desc", orderdesc);
        }

        return "wechat/headhunter/hunter/descForm";
    }

    // 修改服务设置信息
    @OAuthRequired
    @RequestMapping(value = "wechat/hunter/createDesc.do", method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> createDesc(HttpServletRequest request, ModelMap model, OrderDesc dto) {
        Map<String, Object> returnMap = new HashMap<String, Object>();

        HttpSession session = request.getSession();

        String openId = (String) session.getAttribute("OpenId");
        //String openId = "o852Is7ih5u1jnXnLaRixmqWn9zk";
        if (!StringUtils.hasText(openId)) {
            returnMap.put("errorcode", "40001");
            returnMap.put("msg", "必须在微信平台使用我们的服务");
            return returnMap;
        }
        if (dto == null || dto.getName() == null) {
            returnMap.put("errorcode", "40001");
            returnMap.put("msg", "提交参数有错");
            return returnMap;
        }
        Hunter hunter = hunterDAO.getByOpenId(openId);
        OrderDesc orderdesc = new OrderDesc();
        int ordescId;
        int hunterId = hunter.getId();
        // 创建新的服务项目设置
        orderdesc.setName(dto.getName());
        orderdesc.setSpec(dto.getSpec());
        orderdesc.setUnit(dto.getUnit());
        orderdesc.setTag(dto.getTag());
        orderdesc.setRemark(dto.getRemark());
        ordescId = orderDescDAO.save(dto);
        if (ordescId > 0) {
            orderDescDAO.save(hunterId, ordescId, 0, currentTime(), currentTime());
            logger.info("successfully saved the hunter " + hunterId);
            returnMap.put("errorcode", "0");
            returnMap.put("msg", "成功创建了服务设置信息");
            returnMap.put("data", dto);
        } else {
            logger.error("failed to save the hunter " + dto);
            returnMap.put("errorcode", "50001");
            returnMap.put("msg", "创建服务设置信息失败，请添加我们的客服微信（ID:ElenaYu807）联系。");
        }
        return returnMap;
    }

    // 修改服务设置信息
    @OAuthRequired
    @RequestMapping(value = "wechat/hunter/updateDesc.do", method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> updateDesc(HttpServletRequest request, ModelMap model, OrderDesc dto, int id) {
        Map<String, Object> returnMap = new HashMap<String, Object>();

        HttpSession session = request.getSession();

        String openId = (String) session.getAttribute("OpenId");
        //String openId = "o852Is7ih5u1jnXnLaRixmqWn9zk";
        if (!StringUtils.hasText(openId)) {
            returnMap.put("errorcode", "40001");
            returnMap.put("msg", "必须在微信平台使用我们的服务");
            return returnMap;
        }
        if (dto == null || dto.getName() == null) {
            returnMap.put("errorcode", "40001");
            returnMap.put("msg", "提交参数有错");
            return returnMap;
        }
        Hunter hunter = hunterDAO.getByOpenId(openId);
        OrderDesc orderdesc = orderDescDAO.getById(id);
        int ordescId;
        if (hunter != null && orderdesc != null) {
            // 编辑更新
            orderdesc.setName(dto.getName());
            orderdesc.setSpec(dto.getSpec());
            orderdesc.setUnit(dto.getUnit());
            orderdesc.setTag(dto.getTag());
            orderdesc.setRemark(dto.getRemark());
            ordescId = orderDescDAO.update(orderdesc);
            logger.info("update hunter " + hunter);
            //ordescId = hunterDAO.updateProfile(hunter);
            if (ordescId > 0) {
                logger.info("successfully updated the desc " + hunter.getId());
                returnMap.put("errorcode", "0");
                returnMap.put("msg", "成功更新了服务设置信息");
                returnMap.put("data", dto);
            } else {
                logger.error("failed to save the desc " + dto);
                returnMap.put("errorcode", "50001");
                returnMap.put("msg", "更新服务设置信息出错");
            }

        }
        return returnMap;
    }

    //删除服务项目设置
    @OAuthRequired
    @RequestMapping(value = "wechat/hunter/updStatusDesc.do", method = RequestMethod.GET)
    public @ResponseBody
    Map<String, Object> updStatusDesc(HttpServletRequest request, int ordescId, int status, Model model) {
        Map<String, Object> returnMap = new HashMap<String, Object>();
        getCurrentUser(request);
        HttpSession session = request.getSession();
        String openid = (String) session.getAttribute("OpenId");
        // String openid = "o852Is7ih5u1jnXnLaRixmqWn9zk";
        if (openid == null || openid.length() < 1) {
            returnMap.put("errorcode", "1");
            returnMap.put("msg", "openid为空!");
            return returnMap;
        }
        Hunter hunter = hunterDAO.getByOpenId(openid);
        if (hunter != null) {
            int hunterId = hunter.getId();
            if (status == 1) {
                int result = orderDescDAO.updateStatus(status, hunterId, ordescId);
                logger.info("delete service setting result=" + result);
                returnMap.put("errorcode", "0");
                returnMap.put("msg", "该服务项目已发布成功!");
                return returnMap;

            } else if (status == 0) {
                int result = orderDescDAO.delete(hunterId, ordescId);
                logger.info("delete service setting result=" + result);
                returnMap.put("errorcode", "0");
                returnMap.put("msg", "该服务项目已下线!");
                return returnMap;
            }

        }
        logger.error("deldesc is not correct： " + ordescId);
        returnMap.put("errorcode", "40001");
        returnMap.put("msg", "操作服务设置信息失败，请联系我们的客服微信（ID:ElenaYu807）。");
        return returnMap;
    }

    //删除服务项目设置
    @OAuthRequired
    @RequestMapping(value = "wechat/hunter/delDesc.do", method = RequestMethod.GET)
    public @ResponseBody
    Map<String, Object> delDescList(HttpServletRequest request, int ordescId, Model model) {
        Map<String, Object> returnMap = new HashMap<String, Object>();
        getCurrentUser(request);
        HttpSession session = request.getSession();
        String openid = (String) session.getAttribute("OpenId");
        //String openid = "o852Is7ih5u1jnXnLaRixmqWn9zk";
        if (openid == null || openid.length() < 1) {
            returnMap.put("errorcode", "1");
            returnMap.put("msg", "openid为空!");
            return returnMap;
        }
        Hunter hunter = hunterDAO.getByOpenId(openid);
        if (hunter != null) {
            int hunterId = hunter.getId();
            Long count = orderDAO.getCountOfOrderDesc(ordescId);
            if (count > 0) {
                int result = orderDescDAO.update(hunterId, ordescId);
                logger.info("delete service setting result=" + result);
                returnMap.put("errorcode", "0");
                returnMap.put("msg", "删除成功!");
                return returnMap;

            } else {
                int result = orderDescDAO.delete(hunterId, ordescId);
                if (result > 0) {
                    orderDescDAO.delete(ordescId);
                }
                logger.info("delete service setting result=" + result);
                returnMap.put("errorcode", "0");
                returnMap.put("msg", "删除成功!");
                return returnMap;
            }

        }
        logger.error("deldesc is not correct： " + ordescId);
        returnMap.put("errorcode", "40001");
        returnMap.put("msg", "删除信息失败，请联系我们的客服微信（ID:ElenaYu807）。");
        return returnMap;
    }


    /**
     * hr help
     *
     * @param request
     * @param model
     * @return
     */
    @OAuthRequired
    @RequestMapping(value = "wechat/hunter/registerhr.page", method = RequestMethod.GET)
    public String registerHr(HttpServletRequest request, ModelMap model) {
        return "wechat/headhunter/hunter/registerprocesshr";
    }

    /**
     * hunter help
     *
     * @param request
     * @param model
     * @return
     */
    @OAuthRequired
    @RequestMapping(value = "wechat/hunter/registerhunter.page", method = RequestMethod.GET)
    public String registerHunter(HttpServletRequest request, ModelMap model) {
        return "wechat/headhunter/hunter/registerprocess";
    }

    /**
     * consultant help
     *
     * @param request
     * @param model
     * @return
     */
    @OAuthRequired
    @RequestMapping(value = "wechat/hunter/registerconsultant.page", method = RequestMethod.GET)
    public String registerConsultant(HttpServletRequest request, ModelMap model) {
        return "wechat/headhunter/hunter/registerprocesscons";
    }


    public static String currentTime() {
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(System
                .currentTimeMillis());
    }

    public static String currentDate() {
        return new SimpleDateFormat("yyyyMMddHHmmss").format(System
                .currentTimeMillis());
    }

    public static ApiResult sendTemplate(String token, String jsonStr) {
        String jsonResult = HttpUtils.post(WebchatServiceConstant.sendApiUrl
                + token, jsonStr);
        return new ApiResult(jsonResult);
    }


}
